package com.xjt.query.action.interceptor;

import java.net.URLEncoder;

import org.apache.struts2.ServletActionContext;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.WebApplicationContext;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.util.logging.Logger;
import com.opensymphony.xwork2.util.logging.LoggerFactory;
import com.xjt.cache.LoginCache;
import com.xjt.cache.LoginUuidCache;
import com.xjt.common.CookieKey;
import com.xjt.common.PropertyUtils;
import com.xjt.common.ShowConstants;
import com.xjt.common.ShowCookieUtils;
import com.xjt.common.StringUtils;
import com.xjt.query.action.BaseAction;
import com.xjt.query.dao.pojo.QueryUser;
import com.xjt.query.service.interf.LoginService;
import com.xjt.security.Base64;

public class QueryInterceptor extends UrlPaternInterceptor {

    private static final long   serialVersionUID         = -3872954081842039763L;
    private static final Logger log                      = LoggerFactory.getLogger(QueryInterceptor.class);

    // TODO
    private static final String DEFAULT_LOGIN_URL_PREFIX = "http://localhost:8080/";

    @Override
    protected String doIntercept(ActionInvocation invocation) throws Exception {
        Object action = invocation.getAction();
        ApplicationContext applicationContext = (ApplicationContext) ActionContext.getContext().getApplication().get(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
        if (applicationContext == null) {
            log.error("ApplicationContext could not be found,Login validator failed!");
            return null;
        }

        String logonKey = ShowCookieUtils.getCookieValue(CookieKey.LOGIN_KEY);
        LoginCache loginCache = (LoginCache) applicationContext.getBean("loginCache", LoginCache.class);
        LoginUuidCache loginUuidCache = (LoginUuidCache) applicationContext.getBean("loginUuidCache",
                                                                                    LoginUuidCache.class);
        LoginService loginService = (LoginService) applicationContext.getBean("loginService", LoginService.class);
        if (loginCache == null || loginUuidCache == null) {
            return invocation.invoke();
        }

        // 该用户是否已经登录
        if (StringUtils.isNotBlank(logonKey)) {
            Long id = loginCache.get(logonKey);
            // 记住密码功能，如果密码存在cookie中，则自动登录
            QueryUser queryUser = null;
            if (id == null) {
                if (null != loginService) {
                    String userId = ShowCookieUtils.getCookieValue(CookieKey.LOGIN_USER_ID);
                    String pwd = ShowCookieUtils.getCookieValue(ShowCookieUtils.getCookiePwdName(userId));
                    if (StringUtils.isNotBlank(userId) && StringUtils.isNotBlank(pwd)) {
                        queryUser = loginService.doLogin(userId, new String(Base64.decode(pwd)), "1");
                        if (null != queryUser) {
                            id = queryUser.getId();
                        }
                    }
                }
            } else {
                queryUser = loginService.selectUserById(id);
            }
            if (null != id) {
                // 重新设置（防止过期）
                loginCache.put(logonKey, id);
                loginUuidCache.put(id, loginUuidCache.get(id));
                if (action instanceof BaseAction) {
                    ((BaseAction) action).setLoginUser(queryUser);
                }
                // 如果已经登录，则从cookie中取出登录的userId，放入request中;在登录成功后会把当前登录的id写入last_login_id的cookie中
                ServletActionContext.getRequest().setAttribute(ShowConstants.SINGLE_LOGIN_ID, id.toString());
                return invocation.invoke();
            }
        }
        // 未登录的情况下需要先跳转到登录页面，get请求的页面再登录成功后会返回到原来的访问页面
        String baseUrl = PropertyUtils.getUrl("url.query").getDomain();
        if (StringUtils.isBlank(baseUrl)) {
            baseUrl = DEFAULT_LOGIN_URL_PREFIX;
        }
        if (!baseUrl.endsWith("/")) {
            baseUrl += "/";
        }
        String loginUrl = baseUrl + "login.htm";
        if ("GET".equalsIgnoreCase(ServletActionContext.getRequest().getMethod())) {
            String requestURL = ServletActionContext.getRequest().getRequestURL().toString();
            String queryString = ServletActionContext.getRequest().getQueryString();
            StringBuilder sb = new StringBuilder(requestURL);
            if (StringUtils.isNotBlank(queryString)) {
                sb.append("?").append(queryString);
            }
            loginUrl += "?preUrl=" + URLEncoder.encode(sb.toString(), ShowConstants.DEFAULT_ENCODE);
        }
        ActionContext.getContext().getValueStack().set("loginUrl", loginUrl);
        return Action.LOGIN;
    }
}
